package controller

import (
	"fmt"
	"gin_maker_chat/client/handler"
	"gin_maker_chat/model"
	"net/http"
	"sort"

	"github.com/gin-gonic/gin"
)

func LoginIndexController(ctx *gin.Context) {

	//获取用户名和密码err
	username := ctx.PostForm("userName")
	password := ctx.PostForm("passWord")
	//如果验证通过，连接到服务器
	userHandler := &handler.UserHandler{}
	err := userHandler.Login(username, password)
	if err != nil {
		fmt.Println("登录失败，err=", err)
		ctx.HTML(http.StatusOK, "auth-login.html", gin.H{
			"err": err,
		})
		return
	} else {
		fmt.Println("login登录成功")
		//获取在线的用户列表
		var userList []*model.User
		contacts := model.UserSlice{}
		users := handler.UserMgr.ShowOnlineUsers()
		for _, user := range users {
			if user == nil {
				continue
			}
			fmt.Println("用户名===", user.UserName)
			userList = append(userList, user)
			contacts = append(contacts, user)
		}
		sort.Stable(contacts)
		fmt.Println("当前在线的用户users信息：", users)
		fmt.Println("controller-获取到的信息", users)
		ctx.HTML(http.StatusOK, "index.html", gin.H{
			"username": username,
			"users":    contacts,
		})
		// ctx.HTML(http.StatusOK, "index.html", users)
	}

}
